package com.cjf.app;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.UtilsTransActivity;

import java.io.IOException;
import java.util.List;

import hos.location.LocationChangedListener;
import hos.location.LocationData;
import hos.location.LocationEvent;
import hos.location.LocationOnceListener;
import hos.location.LocationPurpose;
import hos.location.LocationSetting;
import hos.location.LocationSourceAndroidData;
import hos.location.LocationSourceManager;
import hos.permission.OnPermissionResultListener;
import hos.permission.PermissionRequest;
import hos.permission.PermissionX;

public class MainActivity extends AppCompatActivity {

    private LocationData location;

    private PermissionRequest permissionX;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        permissionX= PermissionX.init(this);
        // 初始化
        LocationSourceManager.getInstance().init(new LocationSourceAndroidData(this));
        // 设置定位场景
        LocationSourceManager.getInstance().setLocationPurpose(LocationPurpose.Transport);
        // 添加定位监听
        LocationSourceManager.getInstance().addLocationChangedListener(new LocationChangedListener() {
            @Override
            public void locationChanged(LocationEvent.LocationChangedEvent locationChangedEvent) {
                location = locationChangedEvent.getLocation();
                if (location == null) {
                    return;
                }
                LogUtils.eTag("tag", location.toString());
            }
        });
        findViewById(R.id.tvLocation).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取一次定位信息
                LocationSourceManager.getInstance().getOnceLocation(new LocationOnceListener() {
                    @Override
                    public void onLocation(LocationEvent.LocationChangedEvent locationChangedEvent) {
                        LogUtils.eTag("tag", locationChangedEvent.getLocation().toJson());
//                        LocationSetting.runThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                try {
//                                    final List<Address> addressList = locationChangedEvent.getSource().getAddress(locationChangedEvent.getLocation());
//                                    if (addressList != null && !addressList.isEmpty()) {
//                                        for (Address address : addressList) {
//                                            LogUtils.eTag("tag", address.toString());
//                                        }
//                                    }
//                                } catch (IOException e) {
//                                    e.printStackTrace();
//                                }
//                            }
//                        });
                    }
                });
            }
        });

        // 请求定位权限
        permissionX.requestLocation(new OnPermissionResultListener.onSuccessListener() {
            @Override
            public void onSuccess() {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        PermissionManager.setOnPermissionResultListener(requestCode, resultCode, data, new OnPermissionResultListener.onErrorListener() {
//            @Override
//            public void onError(List<String> list) {
//                showRationaleDialog(MainActivity.this, new PermissionUtils.OnRationaleListener.ShouldRequest() {
//                    @Override
//                    public void again(boolean again) {
//                        PermissionManager.requestLocation(MainActivity.this);
//                    }
//                });
//            }
//        }, new OnPermissionResultListener.onSuccessListener() {
//            @Override
//            public void onSuccess() {
//                LocationSourceManager.getInstance().startLocation();
//            }
//        });
    }

    public static void request(
            Context context,
            PermissionUtils.SimpleCallback callback,
            DialogInterface.OnClickListener cancelListener,
            String... permissions
    ) {
        PermissionUtils.permission(permissions)
                .rationale(new PermissionUtils.OnRationaleListener() {
                    @Override
                    public void rationale(@NonNull UtilsTransActivity activity, @NonNull ShouldRequest shouldRequest) {
                        showRationaleDialog(activity, shouldRequest);
                    }
                })
                .callback(new PermissionUtils.SingleCallback() {
                    @Override
                    public void callback(boolean isAllGranted, @NonNull List<String> granted, @NonNull List<String> deniedForever, @NonNull List<String> denied) {
                        if (isAllGranted) {
                            if (callback != null) {
                                callback.onGranted();
                            }
                            return;
                        }
                        if (!deniedForever.isEmpty()) {
                            showOpenAppSettingDialog(context, cancelListener);
                            return;
                        }
                        if (callback != null) {
                            callback.onDenied();
                        }
                    }
                })
                .request();
    }

    private static void showRationaleDialog(
            Context context,
            PermissionUtils.OnRationaleListener.ShouldRequest shouldRequest
    ) {
        String message = "您已经拒绝我们的授权申请，请同意授权，否则该功能无法正常使用! ";
        new AlertDialog.Builder(context)
                .setCancelable(false)
                .setTitle("温馨提示")
                .setMessage(message)
                .setNegativeButton("取消", (dialog, which) -> {
                    shouldRequest.again(false);
                })
                .setPositiveButton("授权", (dialog, which) -> {
                    shouldRequest.again(true);
                })
                .show();
    }

    private static void showOpenAppSettingDialog(Context context, DialogInterface.OnClickListener cancelListener) {
        new AlertDialog.Builder(context)
                .setCancelable(false)
                .setTitle("温馨提示")
                .setMessage("我们需要一些您拒绝的权限或系统申请失败的权限失败，请手动设置为页面授权，否则该功能无法正常使用! ")
                .setNegativeButton("取消", cancelListener)
                .setPositiveButton("授权", (dialog, which) -> {
                    PermissionUtils.launchAppDetailsSettings();
                })
                .show();
    }

    @Override
    protected void onDestroy() {
        // 停止定位
        LocationSourceManager.getInstance().stopLocation();
        super.onDestroy();
    }
}